<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: CollectionRepayTrait.php
// +----------------------------------------------------------------------
// | Author: gxs
// +----------------------------------------------------------------------
// | Description: 催收还款 trait, 必须连接只读库
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2019/3/29 Author: gxs Modification: 创建
// +----------------------------------------------------------------------

namespace App\Models\Collection\Traits;

use App\Constant\RepayConstant;
use App\Models\Collection\RepayReliefRecordModel as CollectionRepayReliefRecordModel;
use App\Models\Collection\RepaySummary as CollectionRepaySummaryModel;
use App\Models\CollectionApiRequest;
use App\Models\RepayRecord as RepayRecordModel;
use App\Models\RepayRecordCommon as RepayRecordCommonModel;
use App\Models\UserGlobal as UserGlobalModel;
use Carbon\Carbon;
use App\Models\SettingChannel as SettingChannelModel;
use App\Models\Collection\RepayRecord as CollectionRepayRecordModel;
use App\Models\Collection\UserLoanRequest as CollectionUserLoanRequestModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 催收系统只读trait
 *
 * Class CollectionRepayTrait
 * @package App\Models\Collection\Traits
 */
Trait CollectionRepayTrait
{
    /**
     * Description: 获取催收数据信息(催收系统专用)
     * Author: Gxs
     * @param $records
     * @param bool $repayRecordBool
     * @return array
     */
    public static function getCollectionInfo($records, $repayRecordBool = false)
    {
        $current_date = Carbon::now()->format('Y-m-d');
        $temp_period_overdue = []; //当前逾期期数
        $temp_success_period = 0; //已还期数
        $temp_overdue_days = 0; //逾期天数
        $temp_fines = 0; //未还罚息
        $temp_amount = 0; //未还剩余本金
        $temp_lending = 0; //未还剩余利息
        $temp_manage = 0; //未还剩余贷后管理费
        $temp_repayment_money_current = 0; //当前已还总额
        $temp_not_repayment_money_current = 0; //当前未还总额
        $temp_not_normal_money = 0; //当前未到还款日总额
        $temp_overdue_time = ''; //最早逾期的起始日
        $relief_amount = ''; //减免金额
        $repayPlanList = []; //还款计划表
        /**
         * 还款记录信息
         */
        $temp_record_repay_money = 0;
        $temp_record_settle_state = 0;
        $temp_record_repay_record_state = 2;
        $temp_record_repay_number = '';
        $temp_record_repay_time = '';
        $temp_record_reduce_money = 0;
        //循环处理订单记录
        array_walk($records, function ($item) use (
            $repayRecordBool,
            &$temp_period_overdue,
            &$temp_success_period,
            &$temp_overdue_days,
            &$temp_fines,
            &$temp_amount,
            &$temp_lending,
            &$temp_manage,
            &$temp_repayment_money_current,
            &$temp_not_repayment_money_current,
            &$temp_not_normal_money,
            &$temp_overdue_time,
            &$relief_amount,
            &$repayPlanList,
            $current_date,
            &$temp_record_repay_money,
            &$temp_record_settle_state,
            &$temp_record_repay_record_state,
            &$temp_record_repay_number,
            &$temp_record_repay_time,
            &$temp_record_reduce_money
        ) {
            $current_not_repayment_money = 0;
            $current_not_normal_money = 0;
            $item['collection_status'] = RepayConstant::COLLECTION_STATUS_THREE;
            if ($item['record_status'] == RepayConstant::STATUS_ONE
                || $item['record_status'] == RepayConstant::STATUS_THREE
            ) {
                //待处理 || 失败的记录
                $item['collection_status'] = RepayConstant::COLLECTION_STATUS_THREE;
                //当前期的未还金额
                $current_not_repayment_money = self::getNotRepaymentMoneyCurrent($item);
                $temp_not_repayment_money_current += $current_not_repayment_money;
                //未还本金
                $temp_amount += $item['record_amount'];
            }
            if (($item['record_status'] == RepayConstant::STATUS_ONE
                    || $item['record_status'] == RepayConstant::STATUS_THREE)
                && $item['normal_date'] > $current_date
            ) {
                //待处理 || 失败的记录 && 未到还款日(包含还款日)
                $current_not_normal_money = self::getNotRepaymentMoneyCurrent($item);
                $temp_not_normal_money += $current_not_normal_money;
                //未还利息和 = 提前结清手续费
                $temp_lending += bcadd($item['money_lending'], $item['common_lending'], 2);
                $temp_manage += bcadd($item['money_manage'], $item['common_manage'], 2);

            }
            if (($item['record_status'] == RepayConstant::STATUS_ONE
                    || $item['record_status'] == RepayConstant::STATUS_THREE)
                && $item['normal_date'] < $current_date
            ) {
                //待处理 || 失败的记录 && 逾期
                $item['collection_status'] = RepayConstant::COLLECTION_STATUS_TWO;
                $temp_period_overdue[] = $item['record_period'];
                //单个最长逾期天数
                if (0 == $temp_overdue_days)
                    $temp_overdue_days = Carbon::parse($item['normal_date'])->diffInDays($current_date, false);
                //计算未还罚息
                $temp_fines += bcadd($item['money_fines'], $item['common_fines'], 2);
                if (empty($temp_overdue_time))
                    $temp_overdue_time = Carbon::parse($item['normal_date'])->addDays(1)->timestamp;
            }
            if ($item['record_status'] == RepayConstant::STATUS_FOUR) {
                //成功的记录
                $item['collection_status'] = RepayConstant::COLLECTION_STATUS_ONE;
                ++$temp_success_period;
                //当前期已还总额
                $current_repayment_money = self::getRepaymentMoneyCurrent($item);
                $temp_repayment_money_current = bcadd($current_repayment_money, $temp_repayment_money_current, 2);

                if ($repayRecordBool) {
                    /**
                     * 还款记录信息
                     */
                    $temp_record_repay_money = $temp_repayment_money_current; //还款金额
                    //是否结清
                    if ($item['record_period'] == $item['period_count']) {
                        $temp_record_settle_state = 1;
                    }
                    if ($item['normal_date'] > $item['repay_date']) {
                        $temp_record_repay_record_state = 1;
                    } else if ($item['normal_date'] == $item['repay_date']) {
                        $temp_record_repay_record_state = 2;
                    } else {
                        //<
                        $temp_record_repay_record_state = 3;
                    }
                    $temp_record_repay_number = '';
                    $temp_record_repay_time = empty($item['repay_date']) ? '' : Carbon::parse($item['repay_date'])->timestamp * 1000;
                    $temp_record_reduce_money = bcdiv($item['common_relief_amount'], 100, 2);
                }
            }
            /**
             * 还款计划表
             */
            $result = self::getRepaymentPlan($item);
            $result['debtMoney'] = bcsub($current_not_repayment_money, $current_not_normal_money, 2);
            $repayPlanList[] = $result;

        });

        /**
         * 还款记录信息
         */
        $repayRecord = [];
        if ($repayRecordBool) {
            $repayRecord['caseCode'] = $records[0]['case_code']; //借款号（案件唯⼀标识）
            $repayRecord['repayMoney'] = $temp_record_repay_money; //还款金额
            $repayRecord['settleState'] = $temp_record_settle_state; //是否结清 1：结清，0：未结清
            $repayRecord['repayRecordState'] = $temp_record_repay_record_state; //还款记录状态（1：提前还款，2：正常还款，3：逾期还款）
            $repayRecord['repayNumber'] = $temp_record_repay_number; //还款流⽔号（还款计划单号）
            $repayRecord['repayTime'] = $temp_record_repay_time; //还款时间
            $repayRecord['reduceMoney'] = $temp_record_reduce_money; //减免金额
        }
        /**
         * 案件信息
         */
        // 结款号
        $case_msg['caseCode'] = $records[0]['case_code'];
        //产品名称
        $case_msg['productName'] = '快闪卡贷';
        //当前逾期期数
        $case_msg['periodOverdue'] = implode(',', $temp_period_overdue);
        //已还期数
        $case_msg['periodRepay'] = $temp_success_period;
        //逾期天数（单个最长逾期时间）
        $case_msg['overdueDay'] = $temp_overdue_days;
        //未还罚息
        $punish_interest_total = bcdiv($temp_fines, 100, 2);
        $case_msg['punishInterestTotal'] = $punish_interest_total;
        //未还剩余本金
        $residual_money = bcdiv($temp_amount, 100, 2);
        $case_msg['residualMoney'] = $residual_money;
        //提前还清手续费 = 未还利息和
        $repayment_money = bcdiv(bcadd($temp_lending, $temp_manage, 2), 100, 2);
        // 结清应还(本金+手续费+罚息)
        $case_msg['settleMoney'] = bcadd(bcadd($punish_interest_total, $residual_money, 2), $repayment_money, 2);
        // 当前已还总额
        $case_msg['repaymentMoneyCurrent'] = $temp_repayment_money_current;
        // 逾期总额
        $debt_money = bcsub($temp_not_repayment_money_current, $temp_not_normal_money, 2);
        $case_msg['debtMoney'] = $debt_money;
        // 逾期起始日
        $case_msg['overdueTime'] = empty($temp_overdue_time) ? '' : $temp_overdue_time * 1000;//转成时间戳(毫秒)

        return [
            'caseMsg' => $case_msg,
            'repayPlanList' => $repayPlanList,
            'repayRecord' => $repayRecord,
        ];
    }

    /**
     * Description: 获取业务系统还款计划表(催收系统专用)
     * Author: Gxs
     * @param $item
     * @return mixed
     */
    public static function getRepaymentPlan($item)
    {
        $current_date = Carbon::now()->format('Y-m-d');
        //还款计划唯一标识
        $repayPlan['repayPlanNumber'] = $item['data_type'] == RepayConstant::DATA_TYPE_TWO ? $item['repay_plan_number'] : 'K2-' . $item['record_id'] . '-' . date('Ymd', strtotime($item['record_create_at']));
        //还款期数
        $repayPlan['periodNumber'] = $item['record_period'];
        //到期还款日期
        $repayPlan['repayTime'] = $item['normal_date'] ? strtotime($item['normal_date']) * 1000 : null;//转成时间戳(毫秒)
        //还款状态
        $repayPlan['repayStatus'] = $item['collection_status'];
        if (RepayConstant::COLLECTION_STATUS_ONE == $item['collection_status']) {
            //当前已还
            $repayPlan['repaymentMoneyCurrent'] = self::getRepaymentMoneyCurrent($item);
            //逾期天数
            $repayPlan['overdueDay'] = 0;
            //本期时间还款日期
            $repayPlan['settleTime'] = !empty($item['repay_date']) ? strtotime($item['repay_date']) * 1000 : null;//转成时间戳（毫秒）
        } else {
            $repayPlan['repaymentMoneyCurrent'] = 0;
            if($item['money_status']==RepayConstant::STATUS_FOUR){
                $repayPlan['repaymentMoneyCurrent'] = bcdiv(($item['record_amount']+$item['money_fines']+$item['money_lending']+$item['money_manage']),100,2);
            }
            $repayPlan['overdueDay'] = Carbon::parse($item['normal_date'])->diffInDays($current_date, false);
            $repayPlan['settleTime'] = null;
        }
        //还款本金
        $repayPlan['principalMoney'] = bcdiv($item['record_amount'], 100, 2);
        //还款利息
        $repayPlan['interestMoney'] = bcdiv(bcadd($item['money_lending'], $item['common_lending'], 2), 100, 2);
        //平台罚息
        $repayPlan['platformPunishInterest'] = bcdiv($item['common_fines'], 100, 2);
        //资方罚息
        $repayPlan['capitalPunishInterest'] = bcdiv($item['money_fines'], 100, 2);
        $total_fines = bcadd($repayPlan['platformPunishInterest'], $repayPlan['capitalPunishInterest'], 2);
        //资方结清违约金 || 平台结清违约金
        if (RepayConstant::PAY_OFF_TWO == $item['repay_pay_off']) {
            $repayPlan['capitalLiquidatedDamage'] = bcdiv(bcadd($item['money_lending'], $item['money_manage'], 2), 100, 2);
            $repayPlan['platformLiquidatedDamage'] = bcdiv(bcadd($item['common_lending'], $item['common_manage'], 2), 100, 2);
        } else {
            $repayPlan['capitalLiquidatedDamage'] = 0;
            $repayPlan['platformLiquidatedDamage'] = 0;
        }
        $total_repayment_money = bcadd($repayPlan['capitalLiquidatedDamage'], $repayPlan['platformLiquidatedDamage'], 2);
        //月保费
        $repayPlan['monthlyPremium'] = bcdiv($item['month_amount'], 100, 2);
        //贷后管理费
        $repayPlan['managementFee'] = bcdiv(bcadd($item['money_manage'], $item['common_manage'], 2), 100, 2);
        //本期账单⾦额(本金+管理费+利息+罚息+月保费+违约金(手续费))
        $repayPlan['periodCurrentBillMoney'] = bcadd(bcadd(bcadd(bcadd(bcadd($repayPlan['principalMoney'], $repayPlan['interestMoney'], 2), $total_fines, 2), $repayPlan['monthlyPremium'], 2), $repayPlan['managementFee'] ,2), $total_repayment_money, 2);
        //本期已还
        if (RepayConstant::STATUS_FOUR == $item['money_status']) {
            $money_repay = bcadd(bcadd(bcadd(bcadd($repayPlan['principalMoney'], $repayPlan['interestMoney'], 2), $repayPlan['capitalPunishInterest'], 2), $item['money_manage'] ,2), $repayPlan['capitalLiquidatedDamage'], 2);
        } else {
            $money_repay = 0;
        }
        if (RepayConstant::STATUS_FOUR == $item['month_status']) {
            $month_repay = $repayPlan['monthlyPremium'];
        } else {
            $month_repay = 0;
        }
        if (RepayConstant::STATUS_FOUR == $item['common_status']) {
            $common_repay = bcadd(bcadd(bcadd($repayPlan['platformPunishInterest'], 2), $item['common_manage'] ,2), $repayPlan['platformLiquidatedDamage'], 2);
        } else {
            $common_repay = 0;
        }
        $total_repay = bcadd(bcadd($money_repay, $common_repay, 2), $month_repay, 2);
        //当前应还
     //   $repayPlan['debtMoney'] = bcsub($repayPlan['periodCurrentBillMoney'], $total_repay, 2);
        $repayPlan['debtMoney'] = bcsub($repayPlan['periodCurrentBillMoney'], $repayPlan['repaymentMoneyCurrent'], 2);
        //罚息减免金额早晨直接置为0
        $repayPlan['reduceMoney'] = 0;
        return $repayPlan;
    }

    /**
     * Description: 已还数据调用,获取当前期已还总额,数据齐全方便后期变更
     * Author: Gxs
     * @param $item
     * @return string|int 单位:元
     */
    public static function getRepaymentMoneyCurrent($item)
    {
        return self::getCurrentPeriodRepaymentMoney($item);
    }

    /**
     * Description: 未还数据调用,获取当前期未还总额,数据齐全,方便后期变更
     * Author: Gxs
     * @param $item
     * @return string|int 单位:元
     */
    public static function getNotRepaymentMoneyCurrent($item)
    {
        return self::getCurrentPeriodRepaymentMoney($item);
    }

    /**
     * Description: 获取这一期的数据表中总额(罚息每日更新，更新完成后表中数据才准确)
     * Author: Gxs
     * @param $item
     * @return string|int 单位:元
     */
    public static function getCurrentPeriodRepaymentMoney($item)
    {
        //本金
        $amount = $item['record_amount'];
        //月保费
        $month_amount = $item['month_amount'];
        //当前期利息
        $lending = bcadd($item['money_lending'], $item['common_lending'], 2); //兼容老数据
        //当前期罚息
        $fines = bcadd($item['money_fines'], $item['common_fines'], 2);
        //当前期管理费
        $manage = bcadd($item['money_manage'], $item['common_manage'], 2);
        $temp1 = bcadd($amount, $lending, 2);
        $temp2 = bcadd($fines, $manage, 2);
        $total = bcdiv(bcadd(bcadd($temp1, $temp2, 2), $month_amount, 2), 100, 2);
        return $total;
    }

    /**
     * Description: 销帐数据逻辑合法性验证
     * Author: Gxs
     * @param $params
     * @return array
     */
    public static function checkWriteOffData($params)
    {
        if (empty($params))
            return ['status' => false, 'response' => ['msg' => '缺少参数','result' => CollectionApiRequest::RESPONSE_PARAM_NOT_FAND]];
        $case_code = $params['caseCode'];
        $period = $params['period'];
        $repay_amount = $params['repayAmount'];

        //获取本次销帐订单
        $summary = CollectionRepaySummaryModel::leftJoin('repay_records as a', 'repay_summaries.id', '=', 'a.summary_id')
            ->leftJoin('repay_record_months as b', 'a.id', '=', 'b.record_id')
            ->leftJoin('repay_record_moneys as c', 'a.id', '=', 'c.record_id')
            ->leftJoin('repay_record_commons as d', 'a.id', '=', 'd.record_id')
            ->select([
                'repay_summaries.id as summary_id',
                'repay_summaries.uid',
                'repay_summaries.data_type',
                'repay_summaries.period_count',
                'repay_summaries.loan_channel',
                'repay_summaries.loan_request_id',
                //a 是repay_records
                'a.id as record_id',
                'a.amount as record_amount',
                'a.period as record_period',
                'a.status as record_status',
                //b 是repay_record_months
                'b.amount as month_amount',
                //c 是repay_record_moneys
                'c.fines_money as money_fines',
                'c.lending_money as money_lending',
                'c.manage_money as money_manage',
                //d 是repay_record_commons
                'd.fines_money as common_fines',
                'd.lending_money as common_lending', //兼容老数据
                'd.manage_money as common_manage',
            ])
            ->where('repay_summaries.loan_id', $case_code)
            ->where('a.period', '>', 0)
            ->where('a.status', '<', '4')
            ->orderBy('a.period', 'asc')
            ->get();
        $summary_array = $summary->toArray();
        if (empty($summary_array))
            return ['status' => false, 'response' => ['msg' => '销帐订单不存在/已完成','result' => CollectionApiRequest::RESPONSE_OTHER_ERROR]];
        $period = array_unique(array_filter(array_values(explode(',', $period))));
        sort($period);
        $periods = array_column($summary_array, 'record_period');
        $period=array_map(function($q){
            return intval($q);
        },$period);
//        if (!empty(array_diff($periods,$period) || $summary->toArray()[0]['record_period']!=$period[0]))
//            return ['status' => false, 'response' => ['msg' => '销帐订单期数异常','result' => CollectionApiRequest::RESPONSE_OTHER_ERROR]];
        //array_diff判断传过来的期数是否不在还款计划表期数中
        if (!empty(array_diff($period,$periods) || $periods[0]!=$period[0]))
            return ['status' => false, 'response' => ['msg' => '销帐订单期数异常','result' => CollectionApiRequest::RESPONSE_OTHER_ERROR]];
        //repayAmount 与 订单所销帐期数总金额对比
        $last_period = 0; //最后一期的期数
//        var_dump($repay_amount);
//        var_dump($summary_array);
//        $test_current_period_amount_yuan = 0;
        $repay_relief_amount = 0;
        $actual_summary_array = [];
        foreach ($summary_array as $key=>$item) {
            if (in_array($item['record_period'], $period)) {
                $actual_summary_array[] = $item;
                $last_period = $item['record_period'];
                //本期账单金额
                $current_period_amount_yuan = CollectionRepayRecordModel::getCurrentPeriodRepaymentMoney($item);
//                $test_current_period_amount_yuan += $current_period_amount_yuan;
                $current_period_amount_fen = (int)bcmul($current_period_amount_yuan, 100);
                //数据库查询的都为分，传输过来的元改为分
                $repay_amount=(int)bcmul($repay_amount, 100);
                $repay_amount -= $current_period_amount_fen;
                //减免金额
                $temp_relief = CollectionRepayReliefRecordModel::getReliefAmount($case_code, $item['record_period']);
                $repay_relief_amount += $temp_relief;
                $balance=$current_period_amount_fen-$repay_amount;
                if($balance>0){
                    //这里是减免
                    RepayRecordCommonModel::where('record_id',$item['record_id'])->update(['relief_amount'=>$balance]);
                }elseif($balance<0){
                    //这里是余额
                    RepayRecordModel::where('id',$item['record_id'])->update(['balance'=>$balance]);
                }
            }
        }
//        var_dump($test_current_period_amount_yuan);exit;
//        var_dump($repay_amount);
//        exit;
        $repay_amount = $repay_amount + $repay_relief_amount;
        //加上减免金额获取 $repay_amount + 减免金额
        if ($repay_amount < 0)
            return ['status' => false, 'response' => ['msg' => '销帐金额少于应还金额','result' => CollectionApiRequest::RESPONSE_OTHER_ERROR]];
        // $repay_amount 为剩余金额
//        var_dump($repay_amount);
        //判断资方
        $data_type = $summary_array[0]['data_type'];
        $loan_channel = $summary_array[0]['loan_channel'];
        $loan_request_id = $summary_array[0]['loan_request_id'];
        if (!in_array($data_type, [RepayConstant::DATA_TYPE_ONE, RepayConstant::DATA_TYPE_TWO]))
            return ['status' => false, 'response' => ['msg' => '系统数据异常','result' => CollectionApiRequest::RESPONSE_OTHER_ERROR]];

        //区分销帐资方
        $money_channel = '';
        if (RepayConstant::DATA_TYPE_ONE == $data_type) {
            //新卡贷数据
            $money_channel = self::_writeOffMoneyChannel($loan_request_id);
        } else if (RepayConstant::DATA_TYPE_TWO == $data_type) {
            //原卡贷数据
            //老数据区分晋商和新光大
            if (SettingChannelModel::CHANNEL_OLD_JINSHANG == $loan_channel) {
                $money_channel = self::_writeOffMoneyChannel($loan_request_id);
            } else if (SettingChannelModel::CHANNEL_OLD_GUANGDA == $loan_channel) {
                //销帐后,通知资方
                $money_channel = RepayConstant::WRITE_OFF_THREE;
            } else {
                //直接销帐
                $money_channel = RepayConstant::WRITE_OFF_FOUR;
            }
        }
        if (empty($money_channel))
            return ['status' => false, 'response' => ['msg' => '系统资方渠道异常','result' => CollectionApiRequest::RESPONSE_OTHER_ERROR]];
        return [
            'status' => true,
            'summary_array' => $actual_summary_array,
            'money_channel' => $money_channel,
            'repay_amount' => $repay_amount,
            'data_type' => $data_type,
            'last_period' => $last_period,
        ];
    }

    /**
     * Description: 销帐当期成功处理(仅限销帐使用)(调用需要事务)
     * Author: Gxs
     * @param $item
     * @return bool
     */
    public static function setCurrentPeriodWriteOff($item)
    {
        $summary_id = $item['summary_id'];
        $record_id = $item['record_id'];
        $uid = $item['uid'];
        $apply_number = $item['apply_number'];
        $period = $item['record_period'];
        $period_count = $item['period_count'];
        $balance = $item['balance'];
        $updateRecord = [
            'apply_number' => $apply_number,
            'status' => RepayConstant::STATUS_FOUR,
            'repay_date' => Carbon::now()->toDateString(), //实际还款日期
            'repay_type' => RepayConstant::REPAY_TYPE_FOUR,//状态改为销账
        ];
        $updateMoney = [
            'status' => RepayConstant::STATUS_FOUR,
            'apply_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'status_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'repay_date' => Carbon::now()->toDateString(), //实际还款日期
            'repay_type' => RepayConstant::REPAY_TYPE_FOUR,//状态改为销账
        ];
        $updateMonth = [
            'status' => RepayConstant::STATUS_FOUR,
            'apply_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'status_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'repay_type' => RepayConstant::REPAY_TYPE_FOUR,//状态改为销账
        ];
        $updateCommon = [
            'status' => RepayConstant::STATUS_FOUR,
            'apply_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'status_time' => Carbon::now()->toDateTimeString(), //实际还款日期
            'repay_type' => RepayConstant::REPAY_TYPE_FOUR,//状态改为销账
        ];
        if ($balance > 0 && $item['last_period'] == $item['record_period']) {
            $updateRecord['balance'] = $balance;
        }
        DB::table('repay_records')->where('id', $record_id)->update($updateRecord);
        DB::table('repay_record_moneys')
            ->where('record_id', $record_id)
            ->where('period', $period)
            ->update($updateMoney);
        DB::table('repay_record_months')
            ->where('record_id', $record_id)
            ->where('period', $period)
            ->update($updateMonth);
        DB::table('repay_record_commons')
            ->where('record_id', $record_id)
            ->where('period', $period)
            ->update($updateCommon);

        if ($period_count == $period) {
            //最后一期完成还款
            DB::table('repay_summaries')->where('id', $summary_id)->update([
                'period' => $period,
                'status' => RepayConstant::STATUS_TWO,
            ]); //summary 摘要表 最终状态变更
            DB::table('user_globals')->where('uid', $uid)->update(['global_status' => UserGlobalModel::STATUS_REPAY_OVER]); //全局状态
        } else {
            DB::table('repay_summaries')->where('id', $summary_id)->update([
                'period' => (int)($period + 1),
            ]); //summary 摘要表
            DB::table('user_globals')->where('uid', $uid)->update(['global_status' => UserGlobalModel::STATUS_REPAY_SUCCESS]); //全局状态
        }
        return true;
    }

    /**
     * Description: 区分销帐资方渠道
     * Author: Gxs
     * @param $loan_request_id
     * @return int|string
     */
    private static function _writeOffMoneyChannel($loan_request_id)
    {
        $money_channel = '';
        $request_channel = CollectionUserLoanRequestModel::where('id', $loan_request_id)
            ->select(['channel'])->value('channel');
        if (RepayConstant::MONEY_CHANNEL_GUANG_DA == $request_channel) {
            $money_channel = RepayConstant::WRITE_OFF_TWO;
        } else if (RepayConstant::MONEY_CHANNEL_JIN_SHANG == $request_channel) {
            $money_channel = RepayConstant::WRITE_OFF_ONE;
        }
        return $money_channel;
    }
}